/**
 * 
 */
package util;

import java.lang.ref.WeakReference;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

/**
 * @author mareshkau
 *
 */
public class HibernateUtil {
    private static WeakReference<SessionFactory> sessionFactory; 
    static{
    	HibernateUtil.buildSession();
    }
    public static SessionFactory getSessionFactory() {
    	if(HibernateUtil.sessionFactory.get()==null){
    		buildSession();
    	}
        return sessionFactory.get();
    }
    
    private static void buildSession() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
        	HibernateUtil.sessionFactory = new WeakReference<SessionFactory>(new AnnotationConfiguration().configure().buildSessionFactory());
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
}